package com.xuxu.blog.controller.loginAndregister;

import com.xuxu.blog.entity.UserEntity;
import com.xuxu.blog.service.impl.InfoServiceImpl;
import com.xuxu.blog.service.impl.UserServiceImpl;
import com.xuxu.blog.service.loginAndregister.EmailService;
import com.xuxu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @className: EmailController
 * @author: Maxuxu
 * @date: 2022/8/23 15:28
 * @description: 登录模块的邮箱验证
 */
@RestController
@Slf4j
@RequestMapping("/blog")
public class EmailController {
    @Autowired
    UserServiceImpl userService;
    @Resource
    EmailService emailService;

    @Autowired
    InfoServiceImpl infoService;

    /**
     * 通过邮件表单信息进行判断
     *
     * @param form
     */
    @PostMapping("/user/login")
    public R LoginByEmail(@RequestBody() UserEntity form) {
        R r = userService.Login(form);
        return r;
    }

    /**
     * 通过邮箱注册信息
     *
     * @return
     */
    @PostMapping("/user/register")
    // public R RegisterByEmail(@RequestBody Map<String, String> registForm) {
    public R RegisterByEmail(@RequestBody UserEntity registForm) {
        boolean register = userService.register(registForm);
         // 如果该用户已经存在则直接返回错误结果。
        if (!register){
            return R.ok("该用户已经存在了，请登录！").put("code", -1);
        }
        int flag = emailService.verifyCode(registForm.getUsername(), registForm.getCode());
        switch (flag){
            case 1:
                return R.ok("注册成功").put("code", flag);
            case 0:
                return R.error("验证码错误").put("code", flag);
            default:
                return R.error("验证码失效,请重新获取验证码").put("code", flag);
        }
    }

    @PostMapping("/user/sendEmail/{email}")
    public R SendEmail(@PathVariable("email") String email,String code) throws Exception {
        boolean b = emailService.verifyCount(email);
        if (b){
            return R.ok("邮件发送成功").put("code",20000);
        }
        return R.error("60分钟只能发送3封").put("code",10000);
    }
}
